<template>
  <div>
    <avue-crud
      :option="tableOption"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="tableOption" @confirm="(val) => $emit('handleSetUserConfig', val)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button size="small" type="primary" :disabled="selectionList.length != 1" v-if="isHasPermission" @click="badHandling">不良处理</el-button>
      </template>
    </avue-crud>

    <el-dialog title="不良处理" v-if="showDialog" append-to-body :visible.sync="showDialog" width="60%" @close="cancelCheck">
      <!-- <el-tabs type="card" v-model="tabsIndex" @tab-click="handleTabClick($event)" v-if="queryParams.documentType === 'OQC'">
        <el-tab-pane label="产 品" name="1"> </el-tab-pane>
        <el-tab-pane label="包 装" name="2"></el-tab-pane>
      </el-tabs> -->
      <avue-form v-if="showDialog" :key="timer" ref="badCodeProperties" v-model="badCodeModel" :option="badCodeOption">
        <template slot="productSequenceNumber">
          <el-input ref="sequenceNumberProperties" placeholder="请输入产品序列号" v-model="badCodeModel.productSequenceNumber" clearable> </el-input>
        </template>
        <template slot="objectSn">
          <el-input ref="objectSnProperties" placeholder="请输入包装条码" v-model="badCodeModel.objectSn" clearable> </el-input>
        </template>
        <!-- <template slot="code">
            <el-input ref="codeProperties" placeholder="请输入不良代码" v-model="badCodeModel.code" clearable @keyup.enter.native="submitBadCode"> </el-input>
          </template> -->
        <template slot="entryBadCode">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="submitBadCode">录 入</el-button>
        </template>
      </avue-form>
      <div class="mark-btn">
        <el-button
          size="small"
          type="primary"
          v-if="(queryParams.documentType === 'OQC' && triggerPoint === 'OQC_BEFORE_INBOUND') || queryParams.documentType === 'FQC' || queryParams.documentType === 'IPQC'"
          @click="markRepair"
          >标记维修</el-button
        >
        <el-button size="small" type="danger" v-if="queryParams.documentType === 'OQC' && triggerPoint === 'OQC_BEFORE_DELIVERY'" @click="markAllow">特许合格</el-button>
        <el-button
          size="small"
          type="danger"
          v-if="queryParams.documentType === 'OQC' || queryParams.documentType === 'FQC' || queryParams.documentType === 'IPQC'"
          @click="markScrap"
          >标记报废</el-button
        >
        <el-button
          size="small"
          type="success"
          v-if="(queryParams.documentType === 'OQC' && triggerPoint === 'OQC_BEFORE_INBOUND') || queryParams.documentType === 'FQC' || queryParams.documentType === 'IPQC'"
          @click="handleFailure"
          >解除不良</el-button
        >
      </div>
      <el-table
        :key="timer"
        height="400"
        :data="dialogData"
        border
        @row-dblclick="rowDblclick"
        style="width: 100%"
        header-row-class-name="header-color"
        :row-class-name="tableRowClassName"
      >
        <el-table-column v-for="item in dialogColumn" :label="item.label" :width="item.width" style="color: #25252" :prop="item.prop" :key="item.prop">
          <template slot-scope="{ row }">
            <span v-if="item.prop === 'objectType'">{{ row[item.prop] | objectTypeFilter }}</span>
            <span v-else>{{ row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <common-modal-template ref="commonModalTemplate" :option="commonTableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </el-dialog>

    <el-dialog append-to-body :title="title" :visible.sync="markModel.showDialog" width="40%" top="5vh">
      <avue-form ref="properties" v-model="properties" :option="propertiesOption" @submit="submitEvent"></avue-form>
    </el-dialog>
  </div>
</template>

<script>
/* eslint max-lines: "off" */ //临时豁免 关闭ESLint的最大代码行数max-lines规则
import { flagRepiar, getProcessRoute } from '@/api/quality/qc-bad-handling.js';
import { getPage } from '@/api/quality/checkLists';
import { getMrodicts } from '@/api/repair/failureconfig';
// import { getAll } from '@/api/repair/repairout.js';
import { getAllByQC, getInspectionPack, markSpecial } from '@/api/repair/repairout.js';
import { flagScrap, flagFailure } from '@/api/repair/failureconfirm';
import { setFailureCodes } from '@/api/repair/failurerecord';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'qc-bad-handling',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  filters: {
    objectTypeFilter(type) {
      switch (type) {
        case 'PRODUCT':
          return '产品';
        case 'PACKING':
          return '包装';
        case 'CARRIER':
          return '载具';
        default:
          break;
      }
    }
  },
  props: {
    tableOption: {
      //表格配置属性
      type: Object,
      default: () => ({})
    },
    dialogColumn: {
      //dialog配置属性
      type: Array,
      default: () => []
    },
    queryParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {},
      model: {},
      query: {},
      loading: true,
      tabsIndex: '1',
      timer: new Date().getTime(),
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      fromRouteOptions: [],
      triggerPoint: '',
      data: [],
      documentId: '',
      selectData: [],
      loadingDialog: true,
      showDialog: false, // 不良处理dialog
      dialogForm: {}, //不良处理存储对象
      dialogData: [],
      badCodeModel: {}, //不良代码存储对象
      badCodeOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true,
            display: true,
            labelWidth: 100,
            span: 6,
            value: '123'
          },
          {
            label: '条码类型',
            prop: 'objectType',
            type: 'select',
            labelWidth: 100,
            display: false,
            span: 6,
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ],
            rules: [
              {
                required: true,
                message: '请输入包装条码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品序列号',
            prop: 'productSequenceNumber',
            labelWidth: 100,
            span: 6,
            rules: [
              {
                required: true,
                message: '请输入产品序列号',
                trigger: 'blur'
              }
            ]
          },

          {
            label: '包装条码',
            prop: 'objectSn',
            labelWidth: 100,
            display: false,
            span: 6,
            rules: [
              {
                required: true,
                message: '请输入包装条码',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '不良代码',
          //   prop: 'code',
          //   span: 6,
          //   type: 'search',
          //   disabled: true,
          //   appendClick: () => {
          //     this.openFailureCodeModal();
          //   },
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入不良代码',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            span: 6,
            label: '',
            prop: 'entryBadCode'
          }
        ]
      },
      badCodes: [], //所有不良代码信息
      title: '',
      properties: {}, //不良处理存储对象
      propertiesOption: {
        labelWidth: '150',
        menuPosition: 'right', //表单菜单按钮的排列方式
        column: []
      },
      markModel: {
        showDialog: false
      },
      commonTableOption: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    },
    isHasPermission() {
      const { documentType } = this.queryParams;
      if (documentType === 'FQC') {
        return this.permission.qcBadHandling_badHanding;
      } else if (documentType === 'IPQC') {
        return this.permission.ipqcBadHandling_badHanding;
      } else {
        return this.permission.oqcBadHandling_badHanding;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    // async handleTabClick({ index }) {
    //   this.newKey();
    //   this.dialogData = [];
    //   const productColumn = this.findObject(this.badCodeOption.column, 'productSequenceNumber');
    //   const objectSnColumn = this.findObject(this.badCodeOption.column, 'objectSn');
    //   const codeColumn = this.findObject(this.badCodeOption.column, 'code');
    //   // this.documentId = this.selectionList[0].id || '';
    //   if (!Number(index)) {
    //     this.tabsIndex = '1';
    //     productColumn.display = true;
    //     objectSnColumn.display = false;
    //     codeColumn.display = true;
    //     // let sequenceNumber = this.selectionList[0].sequenceNumber || '';
    //     this.dialogData = await this.getBadSequenceNumberList({ inspectionDocumentId: this.documentId, statusStr: '1' });
    //     this.focusSequenceNumber();
    //   } else {
    //     this.tabsIndex = '2';
    //     productColumn.display = false;
    //     objectSnColumn.display = true;
    //     codeColumn.display = false;
    //     this.getInspectionPackReq();
    //     // getInspectionPack({ inspectionDocumentId: documentId, isSpecial: false }).then((res) => {
    //     //   this._forEach(res.data.data, (item) => {
    //     //     item.productSequenceNumber = item.objectSn;
    //     //   });
    //     //   this.dialogData = res.data.data;
    //     // });
    //     this.focusObjectSn();
    //   }
    //   this.$emit('handleTabClick', this.tabsIndex);
    // },
    getInspectionPackReq() {
      getInspectionPack({ inspectionDocumentId: this.documentId, isSpecial: false }).then((res) => {
        this._forEach(res.data.data, (item) => {
          item.productSequenceNumber = item.objectSn;
        });
        this.dialogData = res.data.data;
      });
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 不良代码
     */
    openFailureCodeModal() {
      this.$refs.commonModalTemplate.showModal();
      this.commonTableOption = {
        modalTitle: '选择不良代码（双击进行选择）',
        url: '/api/mes-product/mro-dict/page?dictType=BAD_REPAIRE_CODE',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '不良代码',
            prop: 'code',
            search: true
          },
          {
            label: '不良现象描述',
            prop: 'name'
          }
        ]
      };
    },

    /**
     * 选择模态框数据
     */
    async getSelectedRows(rowData, titleInfo) {
      this.badCodeModel.code = rowData.code;
    },
    tableRowClassName({ row, rowIndex }) {
      // let className;
      // if (this.queryParams.documentType !== 'OQC') {
      //   className = row.failureCode && row.entryStatus ? 'scan-entry-row' : '';
      // } else {
      //   className = row.entryStatus ? 'scan-entry-row' : '';
      // }

      return row.entryStatus ? 'scan-entry-row' : '';
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.examineDate && params.examineDate.length > 0) {
        params.startExamineDate = params.examineDate[0];
        params.endExamineDate = params.examineDate[1];
      }
      delete params.examineDate;
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    onLoad(page, params = {}) {
      this.loading = true;
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query, this.queryParams, { descs: 'send_examine_date' })).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    initBadCodes() {
      getMrodicts({ dictType: 'FAILURE' }).then((res) => {
        this.badCodes = res.data.data || [];
      });
    },

    //点击不良处理
    async badHandling() {
      const workOrderNoColumn = this.findObject(this.badCodeOption.column, 'workOrderNo');
      const productColumn = this.findObject(this.badCodeOption.column, 'productSequenceNumber');
      const objectSnColumn = this.findObject(this.badCodeOption.column, 'objectSn');
      const objectTypeColumn = this.findObject(this.badCodeOption.column, 'objectType');
      const codeColumn = this.findObject(this.badCodeOption.column, 'code');
      this.dialogData = [];
      this.documentId = this.selectionList[0].id || '';
      if (this.queryParams.documentType === 'OQC') {
        workOrderNoColumn.display = false;
        codeColumn.display = false;
        this.triggerPoint = this.selectionList[0].triggerPoint;
        if (this.triggerPoint === 'OQC_BEFORE_INBOUND') {
          objectSnColumn.display = false;
          objectTypeColumn.display = true;
          objectSnColumn.display = false;
          productColumn.display = true;
          this.dialogData = await this.getBadSequenceNumberList({ statusStr: '1', inspectionDocumentId: this.documentId });
        } else {
          objectSnColumn.display = true;
          objectTypeColumn.display = false;
          productColumn.display = false;
          this.getInspectionPackReq();
        }
        this.$emit('handleTriggerPoint', this.triggerPoint);
      } else {
        await this.initBadCodes();
        this.dialogData = await this.getBadSequenceNumberList({ statusStr: '1', inspectionDocumentId: this.documentId });
      }

      // this.$emit('handleTabClick', this.tabsIndex);
      this.$set(this.badCodeModel, 'workOrderNo', this.selectionList[0].sourceNo);
      // let sequenceNumber = this.selectionList[0].sequenceNumber || ''; //检验单对应的所有不良序列号id

      this.showDialog = true;
      this.focusSequenceNumber();
    },

    async getBadSequenceNumberList(params) {
      return getAllByQC(params).then((res) => {
        return res.data.data || [];
      });
    },

    // 根据工单id获取工序
    async findWorkOrderNo(workorderId) {
      await getProcessRoute({ workorderId }).then((res) => {
        this.fromRouteOptions = res.data.data.map((d) => {
          return {
            value: d.id,
            label: d.name
          };
        });
        console.log(this.fromRouteOptions, 8888);
      });
    },

    //标记维修
    async markRepair() {
      let scanningList = this.dialogData.filter((item) => item.entryStatus);
      if (scanningList.length === 0) {
        this.$message.warning('请至少录入一条数据');
        return;
      }
      await this.findWorkOrderNo(this.selectionList[0].sourceId);

      this.title = '选择不良原因';
      this.propertiesOption.column = [
        {
          label: '不良产生工序',
          prop: 'badRouteId',
          type: 'select',
          dicData: []
        },
        {
          label: '不良代码',
          prop: 'badFailureId',
          type: 'select',
          dicUrl: '/api/mes-product/mro/dict/list?dictType=FAILURE',
          props: {
            label: 'code',
            value: 'id'
          },
          dicFormatter: (data) => {
            return data.data;
          },
          rules: [
            {
              required: true,
              message: '请选择不良代码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '不良原因大类',
          prop: 'name',
          type: 'select',
          dicUrl: '/api/mes-product/mro-dict/page?dictType=BAD_CAUSE',
          props: {
            label: 'name',
            value: 'id'
          },
          dicFormatter: (data) => {
            return data.data.records;
          },
          cascader: ['subName'],
          rules: [
            {
              required: true,
              message: '请选择不良原因大类',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '不良原因小类',
          prop: 'subName',
          type: 'select',
          dicFlag: false,
          dicUrl: '/api/mes-product/mro/dict/detail?id={{key}}',
          props: {
            label: 'name',
            value: 'id'
          },
          dicFormatter: (data) => {
            return data.data.subList;
          },
          rules: [
            {
              required: true,
              message: '请选择不良原因小类',
              trigger: 'blur'
            }
          ]
        }
      ];
      const badRouteIdColumn = this.findObject(this.propertiesOption.column, 'badRouteId');
      badRouteIdColumn.dicData = this.fromRouteOptions;
      this.markModel.showDialog = true;
    },
    handleFailure() {
      let scanningList = this.dialogData.filter((item) => item.entryStatus);
      if (scanningList.length === 0) {
        this.$message.warning('请至少录入一条数据');
        return;
      }
      this.title = '解除不良原因';
      this.propertiesOption.column = [
        {
          label: '解除不良原因',
          prop: 'reason',
          type: 'textarea',
          maxRows: 3,
          minRows: 3,
          span: 20,
          rules: [
            {
              required: true,
              message: '请输入备注',
              trigger: 'blur'
            }
          ]
        }
      ];
      this.markModel.showDialog = true;
    },
    markAllow() {
      let scanningList = this.dialogData.filter((item) => item.entryStatus);
      if (scanningList.length === 0) {
        this.$message.warning('请至少录入一条数据');
        return;
      }
      this.title = '填写特许合格原因';
      this.propertiesOption.column = [
        {
          label: '特许合格原因',
          prop: 'reason',
          type: 'textarea',
          maxRows: 3,
          minRows: 3,
          span: 20,
          rules: [
            {
              required: true,
              message: '请输入特许合格原因',
              trigger: 'blur'
            }
          ]
        }
      ];
      this.markModel.showDialog = true;
    },
    //标记报废
    markScrap() {
      let scanningList = this.dialogData.filter((item) => item.entryStatus);
      if (scanningList.length === 0) {
        this.$message.warning('请至少录入一条数据');
        return;
      }
      this.title = '填写报废原因';
      this.propertiesOption.column = [
        {
          label: '报废原因',
          prop: 'reason',
          type: 'textarea',
          maxRows: 3,
          minRows: 3,
          span: 20,
          rules: [
            {
              required: true,
              message: '请输入报废原因',
              trigger: 'blur'
            }
          ]
        }
      ];
      this.markModel.showDialog = true;
    },

    //根据序列号录入不良代码
    async submitBadCode() {
      this.$refs.badCodeProperties.validate((valid, done) => {
        if (valid) {
          if (this.triggerPoint === 'OQC_BEFORE_DELIVERY') {
            this.badCodeModel.productSequenceNumber = this.badCodeModel.objectSn;
          }
          //判断输入产品序列号是否存在
          let sequenceIndex = this.dialogData.findIndex((item) => item.productSequenceNumber === this.badCodeModel.productSequenceNumber);
          // let badCodeIndex = 0;
          //

          if (sequenceIndex < 0) {
            let errorMessage = sequenceIndex < 0 ? '未找到该序列号' : '未找到该不良代码';
            this.$message({
              type: 'warning',
              message: errorMessage
            });
            done();
            return;
          }
          this.badCodeEntry(this.badCodeModel.productSequenceNumber, 'input');
          // this.$refs.badCodeProperties.resetForm();
          // this.badCodeModel = {};
          this.badCodeModel.productSequenceNumber = '';
          // this.$set(this.badCodeModel, 'workOrderNo', this.selectionList[0].sourceNo);
          // this.focusSequenceNumber();
          done();
        }
      });
    },

    focusSequenceNumber() {
      this.$nextTick(() => {
        this.$refs.sequenceNumberProperties.focus();
      });
    },
    focusObjectSn() {
      this.$nextTick(() => {
        this.$refs.objectSnProperties.focus();
      });
    },
    //录入序列号双击取消选中
    rowDblclick(row) {
      this.badCodeEntry(row.productSequenceNumber, 'cancel');
      // if (row.failureCode) {

      // }
    },
    /**
     * 不良code录入操作
     *0
     */
    async badCodeEntry(productSequenceNumber, type) {
      let data = this._cloneDeep(this.dialogData);
      let badCodeItem = {};
      // if (this.queryParams.documentType !== 'OQC') {
      //   badCodeItem = this.badCodes.find((item) => item.code === this.badCodeModel.code);
      // }
      let items = [];
      if (this.queryParams.documentType === 'OQC') {
        items = this._remove(data, (item) => {
          return this.triggerPoint === 'OQC_BEFORE_INBOUND'
            ? item.productSequenceNumber === productSequenceNumber && this.badCodeModel.objectType === item.objectType
            : item.productSequenceNumber === productSequenceNumber;
        }).map((item) => {
          // if (this.tabsIndex === '1') {
          //   item.failureCode = type === 'input' ? badCodeItem.code : item.failureCode || '';
          //   item.failureName = type === 'input' ? badCodeItem.name : item.failureName || '';
          // }
          item.entryStatus = type === 'input';
          return item;
        });
      } else {
        items = this._remove(data, (item) => {
          return item.productSequenceNumber === productSequenceNumber;
        }).map((item) => {
          item.entryStatus = type === 'input';
          return item;
        });
      }

      // if (type === 'input' && this.queryParams.documentType !== 'OQC') {
      //   await setFailureCodes(productSequenceNumber, badCodeItem.code, this.badCodeModel.workOrderNo);
      // }
      // console.log(items, 3333333);
      this.dialogData = type === 'input' ? items.concat(data) : data.concat(items);
    },
    //取消不良录入
    cancelCheck() {
      this.$refs.badCodeProperties.resetForm();
      this.badCodeModel = {};
      this.showDialog = false;
    },

    async loadData() {
      // let sequenceNumber = this.selectionList[0].sequenceNumber || ''; //检验单对应的所有不良序列号id
      let documentId = this.selectionList[0].id || '';
      this.dialogData = await this.getBadSequenceNumberList({ inspectionDocumentId: documentId, statusStr: '1' });
      this.showDialog = true;
      this.focusSequenceNumber();
    },

    //报废与维修处理
    submitEvent() {
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          let ids = this.dialogData
            .filter((item) => {
              // if (this.tabsIndex === '1') {
              //   return item.failureCode && item.entryStatus;
              // }
              return item.entryStatus;
            })
            .map((item) => item.id);
          if (this.title === '填写报废原因') {
            flagScrap(ids, this.properties.reason, 0).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
              this.loadData();
            });
            done();
          } else if (this.title === '填写特许合格原因') {
            markSpecial({
              ids: String(ids)
            }).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
              this.getInspectionPackReq();
            });
          } else if (this.title === '解除不良原因') {
            flagFailure(ids, this.properties.reason).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
              this.loadData();
            });
          } else {
            flagRepiar(ids, {
              subCauseId: this.properties.subName,
              badRouteId: this.properties.badRouteId,
              badFailureId: this.properties.badFailureId
            }).then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
              this.loadData();
            });
          }
          this.$refs.properties.resetForm();
          this.markModel.showDialog = false;
          done();
        }
      });
    }
  }
};
</script>

<style scoped>
::v-deep .el-table .header-color {
  color: rgba(0, 0, 0, 0.85) !important;
}

::v-deep .el-table .scan-entry-row {
  background: #caf982;
}

::v-deep .mark-btn {
  margin-bottom: 10px;
}
</style>
